import os
import sys
from pathlib import Path
from gui import create_main_gui, read_verification_code, input_verification_code
from myCryption import validate_license_code
from datetime import datetime
from creat_license import auto_user_license


class Logger:
    def __init__(self, log_file):
        self.log_file = log_file

    def log(self, message):
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        formatted_message = f"{timestamp} - {message}"
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(formatted_message + "\n")


def get_file_path(filename):
    if getattr(sys, 'frozen', False):
        # If running in a bundle (frozen), use the directory where the executable is located
        base_path = Path(sys.executable).parent
    else:
        # If running in a normal Python environment, use the script's directory
        base_path = Path(__file__).parent
    return base_path / filename


def read_create_verification(file_name, logger):
    verification_code = read_verification_code(file_name)
    if verification_code:
        ver_coding = validate_license_code(verification_code)
        if ver_coding:
            logger.log("校验码有效。")
            return True
        else:
            logger.log("校验码无效。")
            return False
    else:
        logger.log("寻找本地校验文件失败，请重新输入校验码")
        if input_verification_code(file_name):
            logger.log("重新输入校验码验证通过")
            return True
        else:
            logger.log("重新输入校验码验证失败")
            return False


def verification_state():
    log_file = get_file_path('application_log.txt')
    logger = Logger(log_file)
    # 获取文件路径
    file_name = get_file_path('verification_code.txt')
    logger.log(f"文件路径为: {file_name}")

    verification_code = auto_user_license()
    if verification_code:
        logger.log("auto_verification_code")  # 校验码为: {verification_code}
        ver_coding = validate_license_code(verification_code, logger)
        if ver_coding:
            logger.log("auto校验码有效。")
            return True
        else:
            logger.log("auto校验码无效。")
            logger.log("寻找本地校验文件")
            return read_create_verification(file_name, logger)
    else:  # 若是校验失败则读取本地校验码
        logger.log("生成校验码失败，开始寻找本地校验文件")
        return read_create_verification(file_name, logger)


def main():
    vacation_state = verification_state()
    if vacation_state:
        create_main_gui()
    print(vacation_state)


if __name__ == "__main__":
    main()
